#include "addfrienddialog.h"
#include "debug.h"
#include "model/datacenter.h"
#include <QLabel>
#include <QFontMetrics>
#include <QPixmap>

using namespace model;

/* -------------------------- 好友搜索窗口 -------------------------- */
AddFriendDialog::AddFriendDialog(QWidget* parent) : QDialog(parent)
{
    // 1. 设置基本属性
    this->setFixedSize(360, 480);
    this->setWindowTitle("添加好友");
    this->setWindowIcon(QIcon(":/resource/image/logo.png"));
    this->setStyleSheet("QDialog {background-color: rgb(247, 247, 247); }");
    this->setAttribute(Qt::WA_DeleteOnClose);

    // 2. 添加布局管理器
    layout = new QGridLayout();
    layout->setSpacing(10);
    layout->setContentsMargins(20, 20, 10, 0);
    this->setLayout(layout);

    // 3. 创建搜索框
    searchEdit = model::createSearchBox(40, "按手机号/用户序号/昵称搜索", 14);
    layout->addWidget(searchEdit, 0, 0, 1, 8);

    // 4. 创建搜索按钮
    QPushButton* searchBtn = new QPushButton("搜索");
    searchBtn->setFixedSize(75, 40);
    searchBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    searchBtn->setStyleSheet(R"(
        QPushButton { border: none; background-color: rgb(7, 193, 96); border-radius: 5px; color: white; font-size: 14px}
        QPushButton:hover { background-color: rgb(6, 183, 91); }
        QPushButton:pressed { background-color: rgb(6, 174, 86); }
    )");
    layout->addWidget(searchBtn, 0, 8, 1, 1);

    // 5. 添加滚动区域
    initResultArea();

// 构造假的数据, 验证界面效果
#if TEST_UI
    QIcon avatar(":/resource/image/yan.png");
    for (int i = 0; i < 20; ++i) {
        // new 出来这个对象, 再往 addResult 中添加. FriendResultItem 中持有了 UserInfo 的 const 引用. 需要确保引用是有效的引用
        UserInfo* userInfo = new UserInfo();
        userInfo->userId = QString::number(1000 + i);
        userInfo->nickname = "张三" + QString::number(i);
        userInfo->description = "这是一段个性签名";
        userInfo->avatar = avatar;
        this->addResult(*userInfo);
    }
#endif

    // 6. 连接信号槽
    connect(searchBtn, &QPushButton::clicked, this, &AddFriendDialog::clickSearchBtn);
}

void AddFriendDialog::initResultArea()
{
    // 1. 创建滚动区域列表容器
    resultContainer = new QWidget();
    resultContainer->setObjectName("resultContainer");
    resultContainer->setStyleSheet("#resultContainer { background-color: transparent;} ");

    // 2. 创建滚动区域内对象
    QScrollArea* scrollArea = model::createScrollArea();
    layout->addWidget(scrollArea, 1, 0, 1, 9);
    // scrollArea->setFrameShape(QFrame::NoFrame);
    // scrollArea->setStyleSheet("background-color: transparent;");
    scrollArea->setWidget(resultContainer);

    // 3. 给这个 QWidget 里面添加元素, 需要给它创建垂直的布局管理器
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setSpacing(0);
    vlayout->setContentsMargins(0, 0, 0, 0);
    resultContainer->setLayout(vlayout);
}


void AddFriendDialog::addResult(const UserInfo &userInfo){
    FriendResultItem* item = new FriendResultItem(userInfo);
    resultContainer->layout()->addWidget(item);
}

void AddFriendDialog::clear(){
    // 从后往前遍历
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(resultContainer->layout());
    for (int i = layout->count() - 1; i >= 0; --i) {
        QLayoutItem* layoutItem = layout->takeAt(i);
        if (layoutItem == nullptr || layoutItem->widget() == nullptr) {
            continue;
        }
        // 删除这里面持有的元素
        delete layoutItem->widget();
    }

    // if (!layout) return;

    // // 使用 while 循环更安全
    // while (QLayoutItem* item = layout->takeAt(0)) {
    //     if (QWidget* widget = item->widget()) {
    //         widget->deleteLater(); // 更安全的删除方式
    //     }
    //     delete item; // 必须删除布局项
    // }
}

void AddFriendDialog::setSearchKey(const QString &searchKey){
    searchEdit->setText(searchKey);
}

void AddFriendDialog::clickSearchBtn(){
    // 1. 拿到输入框内容
    const QString& text = searchEdit->text();
    if(text.isEmpty()) return;

    // 2. 给服务器发送请求
    DataCenter* dataCenter = DataCenter::getInstance();
    connect(dataCenter, &DataCenter::searchUserDone, this, &AddFriendDialog::clickSearchBtnDone, Qt::UniqueConnection);
    dataCenter->searchUserAsync(text);
}

void AddFriendDialog::clickSearchBtnDone(){
    DataCenter* dataCenter = DataCenter::getInstance();
    QList<UserInfo>* searchResult = dataCenter->getSearchUserResult();
    if (searchResult == nullptr) {
        return;
    }

    this->clear();
    for (const auto& u : *searchResult) {
        this->addResult(u);
    }
}


/* -------------------------- 一个好友搜索元素 -------------------------- */
FriendResultItem::FriendResultItem(const UserInfo &userInfo) : userInfo(userInfo)
{
    // 1. 设置基本属性
    this->setFixedHeight(50);
    this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 2. 创建布局管理器
    QGridLayout* layout = new QGridLayout();
    layout->setVerticalSpacing(0);
    layout->setHorizontalSpacing(10);
    layout->setContentsMargins(0, 0, 20, 0);
    this->setLayout(layout);

    // 3. 创建头像
    QPushButton* avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(42, 42);
    avatarBtn->setIconSize(QSize(42, 42));
    QPixmap srcAvatar = userInfo.avatar.pixmap(42, 42);
    srcAvatar = model::getRoundRectPixmap(srcAvatar, QSize(42, 42), 8);
    avatarBtn->setIcon(QIcon(srcAvatar));

    // 4. 创建昵称
    QLabel* nameLabel = new QLabel();
    nameLabel->setFixedHeight(30);
    nameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    nameLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    nameLabel->setStyleSheet("QLabel { color: #333}");
    // 文本截断
    QFontMetrics fmName(QFont("微软雅黑", 14));
    QString elidedName = fmName.elidedText(userInfo.nickname, Qt::ElideRight, 180);
    nameLabel->setText(elidedName);

    // 5. 创建个性签名
    QLabel* descLabel = new QLabel();
    descLabel->setFixedHeight(20);
    descLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    descLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    descLabel->setStyleSheet("QLabel {color: #666}");
    // 文本截断
    QFontMetrics fmDesc(QFont("微软雅黑", 12));
    QString elidedDesc = fmDesc.elidedText(userInfo.description, Qt::ElideRight, 180);
    descLabel->setText(elidedDesc);

    // 6. 创建添加好友按钮
    addBtn = new QPushButton();
    addBtn->setFixedSize(100, 40);
    addBtn->setText("添加好友");
    addBtn->setStyleSheet(R"(
        QPushButton {
            border: none;
            background-color: rgb(137, 217, 97);
            color: white;
            border-radius: 8px;
        }
        QPushButton:pressed {
            background-color: rgb(200, 200, 200);
        }
    )");

    // 7. 把上述内容, 添加到布局管理器中
    layout->addWidget(avatarBtn, 0, 0, 2, 1);
    layout->addWidget(nameLabel, 0, 1);
    layout->addWidget(descLabel, 1, 1);
    layout->addWidget(addBtn, 0, 2, 2, 1);

    // 8. 连接信号槽
    connect(addBtn, &QPushButton::clicked, this, &FriendResultItem::clickAddBtn);
}

void FriendResultItem::clickAddBtn(){
    // 1. 发送好友申请 -- 后续实现

    // 2. 改变按钮状态
    addBtn->setEnabled(false);
    addBtn->setText("已申请");
    addBtn->setStyleSheet(R"(
        QPushButton {
            border:none;
            color: rgb(255, 255, 255);
            background-color: rgb(200, 200, 200);
            border-radius: 8px;
        }
    )");
}
